<template>
  <!-- 搜索栏 -->
  <el-card class="search-card">
    <el-form :model="searchForm" label-width="80px" inline>
      <el-form-item label="工单编号">
        <el-input v-model="searchForm.productionOrderCode" placeholder="工单编号" clearable />
      </el-form-item>
      <el-form-item label="工单名称">
        <el-input v-model="searchForm.productionOrderName" placeholder="工单名称" clearable />
      </el-form-item>
      <el-form-item label="单据来源">
        <el-select style="width: 120px" clearable v-model="searchForm.productionOrderSource" placeholder="单据来源">
          <el-option label="客户订单" :value="1" />
          <el-option label="库存备货" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="物料编号">
        <el-input v-model="searchForm.material.code" placeholder="物料编号" clearable />
      </el-form-item>
      <el-form-item label="物料名称">
        <el-input v-model="searchForm.material.name" placeholder="物料名称" clearable />
      </el-form-item>

      <!-- 搜索栏客户字段-->
      <el-form-item label="客户编号">
        <el-input v-model="searchForm.customer.code" placeholder="客户编号" clearable />
      </el-form-item>
      <el-form-item label="客户名称">
        <el-input v-model="searchForm.customer.name" placeholder="客户名称" clearable />
      </el-form-item>
      <el-form-item label="工单类型">
        <el-select style="width: 120px" clearable v-model="searchForm.productionOrderType" placeholder="工单类型">
          <el-option
              v-for="dictData in productionOrderTypeDictDataList"
              :value="dictData.id"
              :label="dictData.dictLabel"
              :key="dictData.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select style="width: 120px;" v-model="searchForm.status" placeholder="请选择状态" clearable>
          <el-option
              v-for="dictData in productionOrderStatusDictDataList"
              :label="dictData.dictLabel"
              :value="dictData.dictValue"
              :key="dictData.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 工具栏 -->
  <div class="toolbar">
    <el-button type="primary" @click="handleAdd">新增工单</el-button>
    <el-button
        type="danger"
        @click="handleBatchDelete"
        v-if="selectedRows.length > 0 && selectedRows.every(row => getStatusValue(row) === 1)"
    >
      批量删除
    </el-button>
  </div>

  <!-- 列表 -->
  <el-card class="table-card">
    <el-table
        :data="productionOrderList"
        border
        stripe
        @selection-change="handleSelectionChange"
        row-key="id"
        :loading="tableLoading"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="productionOrderCode" label="工单编号">
        <template #default="scope">
          <el-link type="primary" @click="handleDetail(scope.row)">{{ scope.row.productionOrderCode }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="productionOrderName" label="工单名称" />
      <!-- 工单类型 -->
      <el-table-column label="工单类型">
        <template #default="scope">
          <el-tag type="info" v-if="scope.row.productionOrderType">
            {{ getDictLabel(productionOrderTypeDictDataList, scope.row.productionOrderType) }}
          </el-tag>
          <span v-else>--</span>
        </template>
      </el-table-column>
      <el-table-column prop="productionOrderSource" label="工单来源">
        <template #default="scope">
          {{ scope.row.productionOrderSource === 1 ? '客户订单' : '库存备货' }}
        </template>
      </el-table-column>
      <el-table-column prop="orderCode" label="订单编号" />
      <el-table-column prop="materialCode" label="产品/物料编号" />
      <el-table-column prop="material.name" label="产品/物料名称" />
      <el-table-column prop="material.specification" label="规格" />
      <el-table-column prop="material.unit.name" label="单位" />
      <el-table-column prop="productionOrderQuantity" label="工单数量" />
      <!-- 已生产数量 -->
      <el-table-column label="已生产数量">
        <template #default="scope">
          {{ scope.row.producedQuantity || 0 }}
        </template>
      </el-table-column>
      <!-- 客户字段 -->
      <el-table-column prop="customerCode" label="客户编号" />
      <el-table-column prop="customerName" label="客户名称" />
      <el-table-column prop="requestDate" label="需求日期" />
      <el-table-column prop="statusDictData.dictLabel" label="状态">
        <template #default="scope">
          <el-tag :type="getStatusTagType(getStatusValue(scope.row))">
            {{ scope.row.statusDictData?.dictLabel || '--' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="240" fixed="right">
        <template #default="scope">
          <!-- 草稿状态：编辑、删除 -->
          <el-button
              size="small"
              type="primary"
              @click="handleEdit(scope.row)"
              v-if="getStatusValue(scope.row) === 1"
          >
            编辑
          </el-button>
          <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row.id)"
              v-if="getStatusValue(scope.row) === 1"
          >
            删除
          </el-button>

          <!-- 待审核状态：审核、预览 -->
          <el-button
              size="small"
              type="warning"
              @click="handleAudit(scope.row)"
              v-if="getStatusValue(scope.row) === 2"
          >
            审核
          </el-button>
          <el-button
              size="small"
              type="info"
              @click="handlePreview(scope.row)"
              v-if="getStatusValue(scope.row) === 2"
          >
            预览
          </el-button>

          <!-- 已审核通过：预览 -->
          <el-button
              size="small"
              type="info"
              @click="handlePreview(scope.row)"
              v-if="getStatusValue(scope.row) === 3"
          >
            预览
          </el-button>
        </template>
      </el-table-column>

    </el-table>
  </el-card>

  <!-- 分页栏 -->
  <div class="pagination-container">
    <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>

  <!-- 新增/编辑弹窗 -->
  <el-dialog
      :title="dialogTitle"
      v-model="addOrUpdateDialogVisable"
      width="80%"
      :close-on-click-modal="false"
  >
    <el-form
        :model="productionOrderForm"
        label-width="120px"
        ref="productionOrderFormRef"
        :rules="formRules"
    >
      <!-- 工单编号 + 自动生成开关 -->
      <el-form-item label="工单编号" prop="productionOrderCode">
        <div class="flex items-center gap-4">
          <el-input
              v-model="productionOrderForm.productionOrderCode"
              placeholder="请输入工单编号"
              :disabled="isAutoCode || isEdit"
          />
          <el-switch
              v-model="isAutoCode"
              size="large"
              inline-prompt
              active-text="自动生成"
              inactive-text="手动输入"
              @change="autoCode"
              :disabled="isEdit"
          />
        </div>
      </el-form-item>

      <!-- 工单名称 -->
      <el-form-item label="工单名称" prop="productionOrderName">
        <el-input
            v-model="productionOrderForm.productionOrderName"
            placeholder="请输入工单名称"
            maxLength="50"
        />
      </el-form-item>

      <!-- 工单来源 -->
      <el-form-item label="工单来源" prop="productionOrderSource">
        <el-radio-group v-model="productionOrderForm.productionOrderSource">
          <el-radio :label="1">客户订单</el-radio>
          <el-radio :label="2">库存备货</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 订单编号（仅客户订单来源显示） -->
      <el-form-item
          label="订单编号"
          prop="orderCode"
          v-if="productionOrderForm.productionOrderSource === 1"
      >
        <el-input
            v-model="productionOrderForm.orderCode"
            placeholder="请输入关联订单编号"
            maxLength="30"
        />
      </el-form-item>

      <!-- 工单类型 -->
      <el-form-item label="工单类型" prop="productionOrderType">
        <el-select
            v-model="productionOrderForm.productionOrderType"
            placeholder="请选择工单类型"
            style="width: 100%"
        >
          <el-option
              v-for="dictData in productionOrderTypeDictDataList"
              :value="dictData.id"
              :label="dictData.dictLabel"
              :key="dictData.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <!-- 物料信息 - 选择式输入 -->
      <el-form-item label="产品编号" prop="materialCode">
        <div class="flex gap-2">
          <el-input
              v-model="productionOrderForm.materialCode"
              placeholder="请选择产品"
              readonly
              style="flex: 1"
          />
          <el-button type="primary" @click="openProductSelectDialog">选择</el-button>
        </div>
      </el-form-item>
      <el-form-item label="产品名称" prop="material.name">
        <el-input
            v-model="productionOrderForm.material.name"
            placeholder="产品名称"
            readonly
        />
      </el-form-item>
      <el-form-item label="规格型号" prop="material.specification">
        <el-input
            v-model="productionOrderForm.material.specification"
            placeholder="规格型号"
            readonly
        />
      </el-form-item>
      <el-form-item label="计量单位" prop="material.unit.name">
        <el-input
            v-model="productionOrderForm.material.unit.name"
            placeholder="计量单位"
            readonly
        />
      </el-form-item>

      <!-- 工单数量 -->
      <el-form-item label="工单数量" prop="productionOrderQuantity">
        <el-input-number
            v-model="productionOrderForm.productionOrderQuantity"
            :min="1"
            :max="9999999"
            placeholder="请输入工单数量"
        />
      </el-form-item>

      <!-- 需求日期 -->
      <el-form-item label="需求日期" prop="requestDate">
        <el-date-picker
            v-model="productionOrderForm.requestDate"
            type="date"
            placeholder="选择需求日期"
            value-format="YYYY-MM-DD"
            :disabled-date="(date) => date < new Date(new Date().setHours(0, 0, 0, 0))"
        />
      </el-form-item>

      <!-- 客户信息 -->
      <el-form-item label="客户编号" prop="customerCode" v-if="productionOrderForm.productionOrderSource === 1">
        <div class="flex gap-2">
          <el-input
              v-model="productionOrderForm.customerCode"
              placeholder="请选择客户"
              readonly
              style="flex: 1"
          />
          <el-button type="primary" @click="openCustomerSelectDialog">选择</el-button>
        </div>
      </el-form-item>
      <el-form-item label="客户名称" prop="customerName" v-if="productionOrderForm.productionOrderSource === 1">
        <el-input
            v-model="productionOrderForm.customerName"
            placeholder="客户名称"
            readonly
        />
      </el-form-item>

      <!-- 备注 -->
      <el-form-item label="备注">
        <el-input
            type="textarea"
            v-model="productionOrderForm.remark"
            placeholder="请输入备注信息"
            rows="3"
            maxLength="200"
        />
      </el-form-item>
    </el-form>
    <el-card class="bom-material-card" v-if="addOrUpdateDialogVisable">
      <el-tabs type="border-card">
        <el-tab-pane label="BOM组成">
          <!-- 传入工单编号 -->
          <ProductionOrderBom
              v-if="productionOrderForm.productionOrderCode"
              :orderCode="productionOrderForm.productionOrderCode">
          </ProductionOrderBom>
          <div v-else>请先保存工单获取编号后再查看BOM</div>
        </el-tab-pane>
        <el-tab-pane label="物料需求">
          <!-- 传入工单编号 -->
          <ProductionOrderMaterialDemand :orderCode="productionOrderForm.productionOrderCode"></ProductionOrderMaterialDemand>
        </el-tab-pane>
      </el-tabs>
    </el-card>


    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelAddOrUpdate">取消</el-button>
        <!-- 编辑草稿：显示保存、确认 -->
        <el-button
            type="primary"
            @click="submitSave"
            v-if="isEdit && isDraft"
        >
          保存
        </el-button>
        <el-button
            type="success"
            @click="submitConfirm"
            v-if="isEdit && isDraft"
        >
          确认
        </el-button>
        <!-- 新增：显示确定 -->
        <el-button
            type="primary"
            @click="submitProductionOrderForm"
            v-if="!isEdit"
        >
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 详情弹窗 -->
  <el-dialog
      title="工单详情"
      v-model="detailDialogVisable"
      width="80%"
      :close-on-click-modal="false"
  >
    <el-descriptions :column="3" border>
      <el-descriptions-item label="工单编号">{{ detailForm.productionOrderCode }}</el-descriptions-item>
      <el-descriptions-item label="工单名称">{{ detailForm.productionOrderName }}</el-descriptions-item>
      <el-descriptions-item label="工单类型">
        {{ getDictLabel(productionOrderTypeDictDataList, detailForm.productionOrderType) }}
      </el-descriptions-item>
      <el-descriptions-item label="工单来源">{{ detailForm.productionOrderSource === 1 ? '客户订单' : '库存备货' }}</el-descriptions-item>
      <el-descriptions-item label="订单编号">{{ detailForm.orderCode || '-' }}</el-descriptions-item>
      <el-descriptions-item label="工单状态">
        <el-tag :type="getStatusTagType(getStatusValue(detailForm))">{{ detailForm.statusDictData?.dictLabel || '--' }}</el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="物料编号">{{ detailForm.materialCode }}</el-descriptions-item>
      <el-descriptions-item label="物料名称">{{ detailForm.material?.name }}</el-descriptions-item>
      <el-descriptions-item label="规格型号">{{ detailForm.material?.specification || '-' }}</el-descriptions-item>
      <el-descriptions-item label="计量单位">{{ detailForm.material?.unit?.name || '-' }}</el-descriptions-item>
      <el-descriptions-item label="工单数量">{{ detailForm.productionOrderQuantity }}</el-descriptions-item>
      <el-descriptions-item label="已生产数量">{{ detailForm.producedQuantity || 0 }}</el-descriptions-item>
      <el-descriptions-item label="客户编号">{{ detailForm.customerCode || '-' }}</el-descriptions-item>
      <el-descriptions-item label="客户名称">{{ detailForm.customerName || '-' }}</el-descriptions-item>
      <el-descriptions-item label="需求日期">{{ detailForm.requestDate }}</el-descriptions-item>
      <el-descriptions-item label="创建人">{{ detailForm.creatorName || '-' }}</el-descriptions-item>
      <el-descriptions-item label="创建时间">{{ detailForm.createTime }}</el-descriptions-item>
      <el-descriptions-item label="更新时间">{{ detailForm.updateTime || '-' }}</el-descriptions-item>
      <el-descriptions-item label="备注" :span="3">{{ detailForm.remark || '-' }}</el-descriptions-item>
    </el-descriptions>
    <template #footer>
      <el-button @click="detailDialogVisable = false">关闭</el-button>
    </template>
  </el-dialog>
  <!-- 工单 BOM 组成部分 -->
  <el-card class="bom-card" v-if="detailDialogVisable">
    <ProductionOrderBom :orderCode="detailForm.productionOrderCode"></ProductionOrderBom>
  </el-card>

  <!-- 产品选择弹窗 -->
  <el-dialog
      title="选择产品"
      v-model="productSelectDialogVisible"
      width="80%"
      :close-on-click-modal="false"
  >
    <div>
      <!-- 产品搜索栏 -->
      <el-row style="margin: 15px">
        <el-form inline v-model="productSearchForm">
          <el-form-item label="物料编码">
            <el-input v-model="productSearchForm.code" placeholder="物料编码" />
          </el-form-item>
          <el-form-item label="物料名称">
            <el-input v-model="productSearchForm.name" placeholder="物料名称" />
          </el-form-item>
          <el-form-item>
            <el-button size="small" @click="loadProductList">搜索</el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <!-- 产品列表（单选） -->
      <el-row style="margin: 15px">
        <el-radio-group v-model="selectedProductCode">
          <el-table
              :data="productList"
              stripe
              border
              width="100%"
              @row-click="handleProductRowClick"
              :loading="productListLoading"
          >
            <el-table-column>
              <template #default="scope">
                <el-radio :value="scope.row.code" />
              </template>
            </el-table-column>
            <el-table-column prop="code" label="产品编码" />
            <el-table-column prop="name" label="产品名称" />
            <el-table-column prop="specification" label="规格型号" />
            <el-table-column prop="unit.name" label="单位" />
            <el-table-column prop="category.name" label="分类" />
          </el-table>
        </el-radio-group>
      </el-row>
      <el-row style="text-align: right; margin-bottom: 10px">
        <el-button @click="productSelectDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmProductSelect">确定</el-button>
      </el-row>
    </div>
  </el-dialog>

  <!-- 客户选择弹窗 -->
  <el-dialog
      title="选择客户"
      v-model="customerSelectDialogVisible"
      width="80%"
      :close-on-click-modal="false"
  >
    <div>
      <!-- 客户搜索栏 -->
      <el-row style="margin: 15px">
        <el-form inline v-model="customerSearchForm">
          <el-form-item label="客户编码">
            <el-input v-model="customerSearchForm.code" placeholder="客户编码" />
          </el-form-item>
          <el-form-item label="客户名称">
            <el-input v-model="customerSearchForm.name" placeholder="客户名称" />
          </el-form-item>
          <el-form-item>
            <el-button size="small" @click="loadCustomerList">搜索</el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <!-- 客户列表（单选） -->
      <el-row style="margin: 15px">
        <el-radio-group v-model="selectedCustomerCode">
          <el-table
              :data="customerList"
              stripe
              border
              width="100%"
              @row-click="handleCustomerRowClick"
              :loading="customerListLoading"
          >
            <el-table-column>
              <template #default="scope">
                <el-radio :value="scope.row.code" />
              </template>
            </el-table-column>
            <el-table-column prop="code" label="客户编码" />
            <el-table-column prop="name" label="客户名称" />
            <el-table-column prop="contactPerson" label="联系人" />
            <el-table-column prop="phone" label="联系电话" />
            <el-table-column prop="address" label="客户地址" />
          </el-table>
        </el-radio-group>
      </el-row>
      <el-row style="text-align: right; margin-bottom: 10px">
        <el-button @click="customerSelectDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmCustomerSelect">确定</el-button>
      </el-row>
    </div>
  </el-dialog>

  <!-- 审核弹窗 -->
  <el-dialog
      title="工单审核"
      v-model="auditDialogVisible"
      width="80%"
      :close-on-click-modal="false"
  >
    <el-form
        :model="auditForm"
        label-width="120px"
        ref="auditFormRef"
        :rules="auditFormRules"
    >
      <!-- 只读基础信息 -->
      <el-form-item label="工单编号">
        <el-input v-model="auditForm.productionOrderCode" readonly />
      </el-form-item>
      <el-form-item label="工单名称">
        <el-input v-model="auditForm.productionOrderName" readonly />
      </el-form-item>
      <el-form-item label="工单类型">
        <el-input v-model="auditForm.productionOrderTypeName" readonly />
      </el-form-item>
      <el-form-item label="工单来源">
        <el-input v-model="auditForm.productionOrderSourceName" readonly />
      </el-form-item>
      <el-form-item label="订单编号">
        <el-input v-model="formattedOrderCode" readonly />
      </el-form-item>
      <el-form-item label="物料信息">
        <el-input v-model="formattedMaterialInfo" readonly />
      </el-form-item>
      <el-form-item label="工单数量">
        <el-input v-model="auditForm.productionOrderQuantity" readonly />
      </el-form-item>
      <el-form-item label="客户信息">
        <el-input v-model="formattedCustomerCode" readonly />
      </el-form-item>
      <el-form-item label="需求日期">
        <el-input v-model="auditForm.requestDate" readonly />
      </el-form-item>
      <el-form-item label="当前状态">
        <el-tag type="warning">{{ auditForm.statusDictData.dictLabel }}</el-tag>
      </el-form-item>


      <!-- 审核意见（必填） -->
      <el-form-item label="审核意见" prop="auditOpinion">
        <el-input
            type="textarea"
            v-model="auditForm.auditOpinion"
            placeholder="请输入审核意见"
            rows="4"
            maxLength="500"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="auditDialogVisible = false">取消</el-button>
        <el-button type="success" @click="submitAuditPass">审核通过</el-button>
        <el-button type="danger" @click="submitAuditReject">审核不通过</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted, reactive, computed, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getProductionOrderList,
  getAutoCode,
  addProductionOrder,
  deleteProductionOrder,
  updateProductionOrder,
  batchDeleteProductionOrder,
  confirmProductionOrder,
  auditProductionOrder,
  getProductionOrderTypeDictData,
  getProductionOrderStatusDictData
} from "@/api/production-order.js";
import { getMaterialPage } from "@/api/material.js";
import { getCustomerPage } from "@/api/customer.js";
import ProductionOrderBom from "@/views/pro/production-order/ProductionOrderBom.vue";
import ProductionOrderMaterialDemand from "@/views/pro/production-order/ProductionOrderMaterialDemand.vue";


// 1. 表单校验规则
const formRules = reactive({
  productionOrderCode: [
    { required: true, message: "请输入工单编号", trigger: "blur" }
  ],
  productionOrderName: [
    { required: true, message: "请输入工单名称", trigger: "blur" },
    { max: 50, message: "名称长度不能超过50个字符", trigger: "blur" }
  ],
  productionOrderSource: [
    { required: true, message: "请选择工单来源", trigger: "change" }
  ],
  productionOrderType: [
    { required: true, message: "请选择工单类型", trigger: "change" }
  ],
  materialCode: [
    { required: true, message: "请选择产品", trigger: "blur" }
  ],
  "material.name": [
    { required: true, message: "请选择产品", trigger: "blur" }
  ],
  productionOrderQuantity: [
    { required: true, message: "请输入工单数量", trigger: "blur" },
    { type: "number", min: 1, message: "数量不能小于1", trigger: "blur" }
  ],
  requestDate: [
    { required: true, message: "请选择需求日期", trigger: "change" }
  ],
  customerCode: [
    { required: true, message: "请选择客户", trigger: "blur" }
  ],
  customerName: [
    { required: true, message: "请选择客户", trigger: "blur" }
  ],
  orderCode: [
    { required: true, message: "请输入订单编号", trigger: "blur" }
  ]
});

// 审核表单校验规则
const auditFormRules = reactive({
  auditOpinion: [
    { required: true, message: "请输入审核意见", trigger: "blur" },
    { max: 500, message: "审核意见长度不能超过500个字符", trigger: "blur" }
  ]
});

// 2. 响应式数据
const productionOrderFormRef = ref(null);
const auditFormRef = ref(null);
const searchForm = ref({
  productionOrderCode: "",
  productionOrderName: "",
  material: { code: "", name: "" },
  status: null,  // 初始值设为null而非空字符串
  productionOrderSource: "",
  customer: { code: "", name: "" },
  productionOrderType: "",
});
const productionOrderList = ref([]);
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
});
const dialogTitle = ref("新增工单");
const addOrUpdateDialogVisable = ref(false);
const detailDialogVisable = ref(false);
const auditDialogVisible = ref(false);
const isEdit = ref(false);
const isAutoCode = ref(false);
const selectedRows = ref([]);
const tableLoading = ref(false);
const productListLoading = ref(false);
const customerListLoading = ref(false);

// 编辑/新增表单数据
const productionOrderForm = ref({
  id: "",
  productionOrderCode: "",
  productionOrderName: "",
  productionOrderSource: 1,
  productionOrderType: "",
  orderCode: "",
  materialCode: "",
  material: { code: "", name: "", specification: "", unit: { name: "" } },
  productionOrderQuantity: 1,
  producedQuantity: 0,
  customerCode: "",
  customerName: "",
  requestDate: "",
  remark: "",
  status: 1, // 默认为草稿状态
  createTime: "",
  updateTime: ""
});

// 详情表单数据
const detailForm = ref({});

// 审核表单数据
const auditForm = ref({
  productionOrderCode: "",
  productionOrderName: "",
  productionOrderType: "",
  productionOrderTypeName: "",
  productionOrderSource: 1,
  productionOrderSourceName: "客户订单",
  orderCode: "",
  materialCode: "",
  materialName: "",
  productionOrderQuantity: 0,
  customerCode: "",
  requestDate: "",
  statusDictData: {},
  auditOpinion: ""
});

// 字典数据 - 确保初始化为数组
const productionOrderTypeDictDataList = ref([]);
const productionOrderStatusDictDataList = ref([]);

// 产品/客户选择相关数据
const productSelectDialogVisible = ref(false);
const productSearchForm = ref({ code: "", name: "" });
const selectedProductCode = ref("");
const productList = ref([]);
const customerSelectDialogVisible = ref(false);
const customerSearchForm = ref({ code: "", name: "" });
const selectedCustomerCode = ref("");
const customerList = ref([]);

// 计算属性：判断是否为草稿状态
const isDraft = computed(() => {
  return getStatusValue(productionOrderForm.value) === 1;
});

// 审核表单格式化计算属性
const formattedOrderCode = computed(() => {
  return auditForm.value.orderCode || '-';
});

const formattedMaterialInfo = computed(() => {
  return `${auditForm.value.materialCode || ''} - ${auditForm.value.materialName || ''}`;
});

const formattedCustomerCode = computed(() => {
  return auditForm.value.customerCode || '-';
});

// 工具函数：获取状态值（兼容数字和字符串）
const getStatusValue = (row) => {
  // 优先从statusDictData.dictValue获取，没有则从status获取
  let value = row.statusDictData?.dictValue ?? row.status;
  // 转换为数字
  return Number(value) || 0;
};

const getStatusTagType = (statusValue) => {
  switch (Number(statusValue)) {
    case 1:
      return "info"; // 草稿
    case 2:
      return "warning"; // 待审核
    case 3:
      return "success"; // 已审核
    case 4:
      return "danger"; // 已取消
    default:
      return "default";
  }
};

// 安全的字典标签获取函数，关键修改：通过ID匹配字典项
const getDictLabel = (dictList, value) => {
  if (!value) return "--";
  // 确保dictList是数组
  const safeDictList = Array.isArray(dictList) ? dictList : [];
  // 通过id匹配而非dictValue
  const matched = safeDictList.find(item => item.id === value);
  return matched ? matched.dictLabel : value;
};

const resetSearch = () => {
  searchForm.value = {
    productionOrderCode: "",
    productionOrderName: "",
    material: { code: "", name: "" },
    status: null,  // 重置为null而非空字符串
    productionOrderSource: "",
    customer: { code: "", name: "" },
    productionOrderType: "",
  };
  pagination.value.currentPage = 1;
  handleSearch();
};

// 3. 字典加载
const loadProductionOrderStatusDictDataList = () => {
  getProductionOrderStatusDictData().then(res => {
    if (res.code === 200) {
      productionOrderStatusDictDataList.value = res.data || [];
    } else {
      ElMessage.error("工单状态字典加载失败: " + (res.msg || ''));
      productionOrderStatusDictDataList.value = [];
    }
  }).catch(err => {
    console.error('工单状态字典接口错误：', err);
    ElMessage.error("工单状态字典加载异常");
    productionOrderStatusDictDataList.value = [];
  });
};

const loadProductOrderDictDataList = () => {
  getProductionOrderTypeDictData().then(res => {
    if (res.code === 200) {
      productionOrderTypeDictDataList.value = res.data || [];
    } else {
      ElMessage.error("工单类型字典加载失败: " + (res.msg || ''));
      productionOrderTypeDictDataList.value = [];
    }
  }).catch(err => {
    console.error('工单类型字典接口错误：', err);
    ElMessage.error("工单类型字典加载异常");
    productionOrderTypeDictDataList.value = [];
  });
};

// 4. 自动生成编号
const autoCode = () => {
  if (isAutoCode.value) {
    getAutoCode().then(res => {
      if (res.code === 200) {
        productionOrderForm.value.productionOrderCode = res.data;
      } else {
        ElMessage.error(res.msg || "编号生成失败");
        isAutoCode.value = false;
      }
    });
  } else {
    productionOrderForm.value.productionOrderCode = "";
  }
};

// 5. 新增工单
const handleAdd = () => {
  productionOrderForm.value = {
    id: "",
    productionOrderCode: "",
    productionOrderName: "",
    productionOrderSource: 1,
    productionOrderType: "",
    orderCode: "",
    materialCode: "",
    material: { code: "", name: "", specification: "", unit: { name: "" } },
    productionOrderQuantity: 1,
    producedQuantity: 0,
    customerCode: "",
    customerName: "",
    requestDate: "",
    remark: "",
    status: 1
  };
  isEdit.value = false;
  isAutoCode.value = false;
  dialogTitle.value = "新增生产工单";
  addOrUpdateDialogVisable.value = true;
  // 确保组件已挂载后再调用方法
  nextTick(() => {
    productionOrderFormRef.value?.clearValidate();
  });
};

// 6. 编辑工单（仅草稿状态可编辑）
const handleEdit = (row) => {
  if (getStatusValue(row) !== 1) {
    ElMessage.warning("仅草稿状态的工单可编辑");
    return;
  }
  productionOrderForm.value = JSON.parse(JSON.stringify(row));
  productionOrderForm.value.customerCode = row.customerCode || "";
  productionOrderForm.value.customerName = row.customerName || "";
  productionOrderForm.value.material = productionOrderForm.value.material || {
    code: "",
    name: "",
    specification: "",
    unit: { name: "" }
  };
  isEdit.value = true;
  isAutoCode.value = false;
  dialogTitle.value = "编辑生产工单";
  addOrUpdateDialogVisable.value = true;
  // 确保组件已挂载后再调用方法
  nextTick(() => {
    productionOrderFormRef.value?.clearValidate();
  });
};

// 7. 详情弹窗
const handleDetail = (row) => {
  detailForm.value = JSON.parse(JSON.stringify(row));
  detailForm.value.customerCode = row.customerCode || "";
  detailForm.value.customerName = row.customerName || "";
  detailDialogVisable.value = true;
};

// 8. 表单提交（新增）
const submitProductionOrderForm = () => {
  productionOrderFormRef.value.validate((isValid) => {
    if (!isValid) return;

    const submitData = {
      id: productionOrderForm.value.id,
      productionOrderCode: productionOrderForm.value.productionOrderCode,
      productionOrderName: productionOrderForm.value.productionOrderName,
      productionOrderSource: productionOrderForm.value.productionOrderSource,
      productionOrderType: productionOrderForm.value.productionOrderType,  // 提交字典ID
      orderCode: productionOrderForm.value.productionOrderSource === 1 ? productionOrderForm.value.orderCode : "",
      materialCode: productionOrderForm.value.materialCode,
      material: {
        name: productionOrderForm.value.material.name,
        specification: productionOrderForm.value.material.specification,
        unit: { name: productionOrderForm.value.material.unit.name }
      },
      productionOrderQuantity: productionOrderForm.value.productionOrderQuantity,
      customerCode: productionOrderForm.value.productionOrderSource === 1 ? productionOrderForm.value.customerCode : null,
      customerName: productionOrderForm.value.productionOrderSource === 1 ? productionOrderForm.value.customerName : null,
      requestDate: productionOrderForm.value.requestDate,
      remark: productionOrderForm.value.remark,
      status: 1 // 新增默认草稿状态
    };

    addProductionOrder(submitData).then(res => {
      if (res.code === 200) {
        ElMessage.success("新增成功");
        addOrUpdateDialogVisable.value = false;
        handleSearch();
      } else {
        ElMessage.error(res.msg || "新增失败");
      }
    });
  });
};

// 9. 保存修改（不改变状态）
const submitSave = () => {
  productionOrderFormRef.value.validate((isValid) => {
    if (!isValid) return;

    const submitData = {
      id: productionOrderForm.value.id,
      productionOrderCode: productionOrderForm.value.productionOrderCode,
      productionOrderName: productionOrderForm.value.productionOrderName,
      productionOrderSource: productionOrderForm.value.productionOrderSource,
      productionOrderType: productionOrderForm.value.productionOrderType,  // 提交字典ID
      orderCode: productionOrderForm.value.productionOrderSource === 1 ? productionOrderForm.value.orderCode : "",
      materialCode: productionOrderForm.value.materialCode,
      material: {
        name: productionOrderForm.value.material.name,
        specification: productionOrderForm.value.material.specification,
        unit: { name: productionOrderForm.value.material.unit.name }
      },
      productionOrderQuantity: productionOrderForm.value.productionOrderQuantity,
      customerCode: productionOrderForm.value.productionOrderSource === 1 ? productionOrderForm.value.customerCode : null,
      customerName: productionOrderForm.value.productionOrderSource === 1 ? productionOrderForm.value.customerName : null,
      requestDate: productionOrderForm.value.requestDate,
      remark: productionOrderForm.value.remark,
      status: 1 // 保持草稿状态
    };

    updateProductionOrder(submitData).then(res => {
      if (res.code === 200) {
        ElMessage.success("保存成功");
        addOrUpdateDialogVisable.value = false;
        handleSearch();
      } else {
        ElMessage.error(res.msg || "保存失败");
      }
    });
  });
};

// 10. 确认工单（草稿→待审核）
const submitConfirm = () => {
  productionOrderFormRef.value.validate((isValid) => {
    if (!isValid) return;

    ElMessageBox.confirm(
        "确认后工单将进入待审核状态，不可再编辑，是否继续？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
    ).then(() => {
      const submitData = {
        id: productionOrderForm.value.id,
        productionOrderCode: productionOrderForm.value.productionOrderCode,
        productionOrderName: productionOrderForm.value.productionOrderName,
        productionOrderSource: productionOrderForm.value.productionOrderSource,
        productionOrderType: productionOrderForm.value.productionOrderType,  // 提交字典ID
        orderCode: productionOrderForm.value.productionOrderSource === 1 ? productionOrderForm.value.orderCode : "",
        materialCode: productionOrderForm.value.materialCode,
        material: {
          name: productionOrderForm.value.material.name,
          specification: productionOrderForm.value.material.specification,
          unit: { name: productionOrderForm.value.material.unit.name }
        },
        productionOrderQuantity: productionOrderForm.value.productionOrderQuantity,
        customerCode: productionOrderForm.value.productionOrderSource === 1 ? productionOrderForm.value.customerCode : null,
        customerName: productionOrderForm.value.productionOrderSource === 1 ? productionOrderForm.value.customerName : null,
        requestDate: productionOrderForm.value.requestDate,
        remark: productionOrderForm.value.remark,
        status: 2 // 待审核状态
      };

      updateProductionOrder(submitData).then(res => {
        if (res.code === 200) {
          ElMessage.success("确认成功");
          addOrUpdateDialogVisable.value = false;
          handleSearch();
        } else {
          ElMessage.error(res.msg || "确认失败");
        }
      });
    });
  });
};

// 11. 取消弹窗
const cancelAddOrUpdate = () => {
  addOrUpdateDialogVisable.value = false;
  nextTick(() => {
    productionOrderFormRef.value?.clearValidate();
  });
};

// 12. 删除工单（仅草稿状态）
const handleDelete = (id) => {
  ElMessageBox.confirm(
      "此操作将永久删除该工单，是否继续？",
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
  ).then(() => {
    deleteProductionOrder(id).then(res => {
      if (res.code === 200) {
        ElMessage.success("删除成功");
        handleSearch();
      } else {
        ElMessage.error(res.msg || "删除失败");
      }
    });
  }).catch(() => {
    ElMessage.info("已取消删除");
  });
};

// 13. 批量删除（仅草稿状态）
const handleBatchDelete = () => {
  const ids = selectedRows.value.map(row => row.id).join(",");
  ElMessageBox.confirm(
      `此操作将永久删除选中的${selectedRows.value.length}条工单，是否继续？`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
  ).then(() => {
    batchDeleteProductionOrder(ids).then(res => {
      if (res.code === 200) {
        ElMessage.success("批量删除成功");
        selectedRows.value = [];
        handleSearch();
      } else {
        ElMessage.error(res.msg || "批量删除失败");
      }
    });
  }).catch(() => {
    ElMessage.info("已取消删除");
  });
};

// 14. 预览工单
const handlePreview = (row) => {
  handleDetail(row); // 复用详情弹窗作为预览
};

// 15. 列表行确认操作（草稿→待审核）
const handleConfirm = (row) => {
  if (getStatusValue(row) !== 1) {
    ElMessage.warning("仅草稿状态的工单可确认");
    return;
  }

  ElMessageBox.confirm(
      "确认后工单将进入待审核状态，不可再编辑，是否继续？",
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
  ).then(() => {
    const submitData = {
      id: row.id,
      status: 2 // 待审核状态
    };

    updateProductionOrder(submitData).then(res => {
      if (res.code === 200) {
        ElMessage.success("确认成功");
        handleSearch();
      } else {
        ElMessage.error(res.msg || "确认失败");
      }
    });
  });
};

// 16. 打开审核弹窗（仅待审核状态）
const handleAudit = (row) => {
  if (getStatusValue(row) !== 2) {
    ElMessage.warning("仅待审核状态的工单可审核");
    return;
  }
  // 填充审核表单数据
  auditForm.value = {
    productionOrderCode: row.productionOrderCode,
    productionOrderName: row.productionOrderName,
    productionOrderType: row.productionOrderType,
    productionOrderTypeName: getDictLabel(productionOrderTypeDictDataList, row.productionOrderType),
    productionOrderSource: row.productionOrderSource,
    productionOrderSourceName: row.productionOrderSource === 1 ? "客户订单" : "库存备货",
    orderCode: row.orderCode,
    materialCode: row.materialCode,
    materialName: row.material?.name || "",
    productionOrderQuantity: row.productionOrderQuantity,
    customerCode: row.customerCode || "",
    requestDate: row.requestDate,
    statusDictData: JSON.parse(JSON.stringify(row.statusDictData)),
    auditOpinion: ""
  };
  currentAuditId.value = row.id;
  auditDialogVisible.value = true;
  nextTick(() => {
    auditFormRef.value?.clearValidate();
  });
};

// 17. 审核通过（待审核→已审核）
const submitAuditPass = () => {
  auditFormRef.value.validate((isValid) => {
    if (!isValid) return;

    // 获取当前登录用户ID（实际项目中应从全局状态获取）
    const updatorId = 1; // 示例值

    auditProductionOrder(currentAuditId.value, 1, auditForm.value.auditOpinion, updatorId).then(res => {
      if (res.code === 200) {
        ElMessage.success("审核通过成功");
        auditDialogVisible.value = false;
        handleSearch();
      } else {
        ElMessage.error(res.msg || "审核失败");
      }
    });
  });
};

// 18. 审核不通过（待审核→草稿）
const submitAuditReject = () => {
  auditFormRef.value.validate((isValid) => {
    if (!isValid) return;

    // 获取当前登录用户ID（实际项目中应从全局状态获取）
    const updatorId = 1; // 示例值

    auditProductionOrder(currentAuditId.value, 0, auditForm.value.auditOpinion, updatorId).then(res => {
      if (res.code === 200) {
        ElMessage.success("审核不通过，工单已回退至草稿状态");
        auditDialogVisible.value = false;
        handleSearch();
      } else {
        ElMessage.error(res.msg || "审核失败");
      }
    });
  });
};

// 19. 列表选择事件
const handleSelectionChange = (val) => {
  selectedRows.value = val;
};

// 20. 搜索工单列表 - 确保status参数正确传递
const handleSearch = () => {
  tableLoading.value = true;
  // 转换status为Number类型，如果是空则设为null
  const statusValue = searchForm.value.status !== null && searchForm.value.status !== ''
      ? Number(searchForm.value.status)
      : null;

  const params = {
    ...searchForm.value,
    pageNum: pagination.value.currentPage,
    pageSize: pagination.value.pageSize,
    materialCode: searchForm.value.material.code,
    materialName: searchForm.value.material.name,
    customerCode: searchForm.value.customer.code,
    customerName: searchForm.value.customer.name,
    status: statusValue  // 传递转换后的数值类型状态值
  };
  delete params.material;
  delete params.customer;

  getProductionOrderList(params).then(res => {
    tableLoading.value = false;
    if (res.code === 200) {
      productionOrderList.value = Array.isArray(res.data.list) ? res.data.list : [];
      pagination.value.total = res.data.total || 0;
    } else {
      ElMessage.error(res.msg || "工单列表加载失败");
      productionOrderList.value = [];
      pagination.value.total = 0;
    }
  }).catch(err => {
    tableLoading.value = false;
    console.error('工单列表接口错误：', err);
    ElMessage.error("工单列表加载异常");
  });
};

// 21. 分页事件
const handleSizeChange = (pageSize) => {
  pagination.value.pageSize = pageSize;
  handleSearch();
};

const handleCurrentChange = (newPage) => {
  pagination.value.currentPage = newPage;
  handleSearch();
};

// 22. 产品选择相关
const openProductSelectDialog = () => {
  productSelectDialogVisible.value = true;
  loadProductList();
};

const loadProductList = () => {
  productListLoading.value = true;
  getMaterialPage(1, 10000, productSearchForm.value).then((res) => {
    productListLoading.value = false;
    if (res.code === 200) {
      productList.value = Array.isArray(res.data.list) ? res.data.list : [];
    } else {
      ElMessage.error(res.msg || "产品列表加载失败");
    }
  }).catch(err => {
    productListLoading.value = false;
    console.error('产品列表接口错误：', err);
    ElMessage.error("产品列表加载异常");
  });
};

const handleProductRowClick = (row) => {
  selectedProductCode.value = row.code;
};

const confirmProductSelect = () => {
  if (!selectedProductCode.value) {
    ElMessage.warning("请选择产品");
    return;
  }

  const selectedProduct = productList.value.find(
      (item) => item.code === selectedProductCode.value
  );

  if (selectedProduct) {
    productionOrderForm.value.materialCode = selectedProduct.code;
    productionOrderForm.value.material.name = selectedProduct.name;
    productionOrderForm.value.material.specification = selectedProduct.specification;
    productionOrderForm.value.material.unit.name = selectedProduct.unit?.name || '';
    productSelectDialogVisible.value = false;
    nextTick(() => {
      productionOrderFormRef.value.validateField(['materialCode', 'material.name']);
    });
  } else {
    ElMessage.error("未找到选中的产品");
  }
};

// 23. 客户选择相关
const openCustomerSelectDialog = () => {
  customerSelectDialogVisible.value = true;
  loadCustomerList();
};

const loadCustomerList = () => {
  customerListLoading.value = true;
  getCustomerPage(1, 10000, customerSearchForm.value).then((res) => {
    customerListLoading.value = false;
    if (res.code === 200) {
      customerList.value = Array.isArray(res.data.list) ? res.data.list : [];
    } else {
      ElMessage.error(res.msg || "客户列表加载失败");
    }
  }).catch(err => {
    customerListLoading.value = false;
    console.error('客户列表接口错误：', err);
    ElMessage.error("客户列表加载异常");
  });
};

const handleCustomerRowClick = (row) => {
  selectedCustomerCode.value = row.code;
};

const confirmCustomerSelect = () => {
  if (!selectedCustomerCode.value) {
    ElMessage.warning("请选择客户");
    return;
  }

  const selectedCustomer = customerList.value.find(
      (item) => item.code === selectedCustomerCode.value
  );

  if (selectedCustomer) {
    productionOrderForm.value.customerCode = selectedCustomer.code;
    productionOrderForm.value.customerName = selectedCustomer.name;
    customerSelectDialogVisible.value = false;
    nextTick(() => {
      productionOrderFormRef.value.validateField(['customerCode', 'customerName']);
    });
  } else {
    ElMessage.error("未找到选中的客户");
  }
};

// 24. 页面初始化
onMounted(() => {
  loadProductionOrderStatusDictDataList();
  loadProductOrderDictDataList();
  handleSearch();
});

// 25. 当前审核的工单ID
const currentAuditId = ref(null);
</script>

<style scoped>
.search-card {
  margin-bottom: 20px;
}

.toolbar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.flex {
  display: flex;
}

.items-center {
  align-items: center;
}

.gap-4 {
  gap: 16px;
}

.gap-2 {
  gap: 8px;
}

.el-descriptions-item {
  word-break: break-all;
}

/* 审核表单样式 */
.audit-form {
  margin-bottom: 20px;
}

.audit-form .el-form-item {
  margin-bottom: 16px;
}

/* 加载状态样式 */
.el-table__empty-text,
.el-loading-mask {
  z-index: 1;
}
</style>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}
</style>
